package com.example.pda_scan

import androidx.annotation.NonNull

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** PdaScanPlugin */
class PdaScanPlugin: FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private lateinit var receiver: BroadcastReceiver

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "pda_scan")

    // 注册 BroadcastReceiver
    val filter = IntentFilter().apply {
      addAction("cn.rq.pda.action.receivescan")
      addAction("com.android.server.scannerservice.broadcast")
    }

    receiver = object : BroadcastReceiver() {
      override fun onReceive(context: Context?, intent: Intent?) {
        val barcode = intent?.getStringExtra("barcode") ?: intent?.getStringExtra("scannerdata")
        barcode?.let {
          channel.invokeMethod("scanCode", it)
        }
      }
    }

    flutterPluginBinding.applicationContext.registerReceiver(receiver, filter)

  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    if (call.method == "getPlatformVersion") {
      result.success("Android ${android.os.Build.VERSION.RELEASE}")
    } else {
      result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
    binding.applicationContext.unregisterReceiver(receiver)
  }
}
